using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    /// <summary>
    /// 订单详情仓储实现
    /// </summary>
    public class OrderDetailRepository : Repository<OrderDetail, Guid>, IOrderDetailRepository
    {
        public OrderDetailRepository(ApplicationDbContext context)
            : base(context) { }

        /// <summary>
        /// 获取订单的所有详情
        /// </summary>
        public async Task<List<OrderDetail>> GetByOrderIdAsync(Guid orderId)
        {
            return await _context
                .OrderDetails.AsNoTracking()
                .Include(od => od.TeacherSchedule)
                .Include(od => od.TeacherSchedule.Course)
                .Where(od => od.OrderId == orderId)
                .ToListAsync();
        }

        public async Task<OrderDetail> GetByIdAsync(Guid id)
        {
            return await _context.OrderDetails.AsNoTracking()
                .Include(od => od.TeacherSchedule)
                .FirstOrDefaultAsync(od => od.Id == id);
        }

        /// <summary>
        /// 根据教师课表ID获取订单详情
        /// </summary>
        public async Task<List<OrderDetail>> GetByTeacherScheduleIdAsync(Guid teacherScheduleId)
        {
            return await _context
                .OrderDetails.AsNoTracking()
                .Include(od => od.Order)
                .Include(od => od.TeacherSchedule)
                .Include(od => od.Student)
                .Where(od => od.TeacherScheduleId == teacherScheduleId)
                .ToListAsync();
        }

        /// <summary>
        /// 批量添加订单详情
        /// </summary>
        public async Task AddRangeAsync(List<OrderDetail> orderDetails)
        {
            await _context.OrderDetails.AddRangeAsync(orderDetails);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 批量删除订单详情
        /// </summary>
        public async Task DeleteRangeAsync(List<OrderDetail> orderDetails)
        {
            _context.OrderDetails.RemoveRange(orderDetails);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 根据订单ID、学生ID和教师课表ID获取订单详情
        /// </summary>
        public async Task<OrderDetail> GetByOrderIdAndStudentIdAndTeacherScheduleIdAsync(
            Guid orderId,
            Guid studentId,
            Guid teacherScheduleId
        )
        {
            return await _context.OrderDetails
                .AsNoTracking()
                .FirstOrDefaultAsync(od =>
                    od.OrderId == orderId
                    && od.StudentId == studentId
                    && od.TeacherScheduleId == teacherScheduleId
                );
        }

        /// <summary>
        /// 分页查询订单详情
        /// </summary>
        public async Task<PagedResult<OrderDetail>> GetPagedAsync(OrderDetailPageRequest request)
        {
            //TODO: 如果学生不存在，则不包含
            var query = _context.OrderDetails
                .AsNoTracking()
                .Include(od => od.Student).Where(o => !o.Student.IsDeleted)
                .Include(od => od.StudentScheduleDetails)
                .AsQueryable();

            // 应用过滤条件
            if (request.OrderId.HasValue)
            {
                query = query.Where(od => od.OrderId == request.OrderId.Value);
            }

            if (request.StudentId.HasValue)
            {
                query = query.Where(od => od.StudentId == request.StudentId.Value);
            }

            if (request.TeacherScheduleId.HasValue)
            {
                query = query.Where(od => od.TeacherScheduleId == request.TeacherScheduleId.Value);
            }

            // 日期范围过滤
            if (request.StartDate.HasValue && request.EndDate.HasValue)
            {
                query = query.Where(od =>
                    od.TeacherSchedule.StartTime >= request.StartDate.Value
                    && od.TeacherSchedule.EndTime <= request.EndDate.Value.AddDays(1).AddSeconds(-1)
                );
            }
            else if (request.StartDate.HasValue)
            {
                query = query.Where(od => od.TeacherSchedule.StartTime >= request.StartDate.Value);
            }
            else if (request.EndDate.HasValue)
            {
                query = query.Where(od =>
                    od.TeacherSchedule.EndTime <= request.EndDate.Value.AddDays(1).AddSeconds(-1)
                );
            }

            // 计算总数
            var total = await query.CountAsync();

            // 应用分页
            var items = await query
                .OrderBy(od => od.Order.Student.StudentNo)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync();

            return new PagedResult<OrderDetail> { Items = items, Total = total };
        }

        /// <summary>
        /// 根据学生ID获取订单详情
        /// </summary>
        public async Task<List<OrderDetail>> GetByStudentIdAsync(Guid id)
        {
            return await _context.OrderDetails
                .AsNoTracking()
                .Include(od => od.Student).Where(o => !o.Student.IsDeleted)
                .Where(od => od.StudentId == id)
                .ToListAsync();
        }
    }
}
